<template>
  <!---搜索表单-->
    <div class="search-div">
        <el-form label-width="70px" size="small">
            <el-row>
                <el-col :span="6">
                    <el-form-item label="课程名称">
                        <el-input v-model="queryDto.name" style="width: 100%" placeholder="请输入课程名称"/>
                    </el-form-item>
                </el-col>
                <el-col :span="6">
                    <el-form-item label="开课学院">
                        <el-select v-model="queryDto.collegeId" placeholder="请选择" style="width: 100%">
                            <el-option v-for="item in collegeOptions" :key="item.id" :label="item.name"
                                       :value="item.id"/>
                        </el-select>
                    </el-form-item>
                </el-col>
                <el-col :span="6">
                    <el-form-item label="课程类型">
                        <el-select v-model="queryDto.category" placeholder="请选择" style="width: 100%">
                            <el-option v-for="item in categoryOptions" :key="item.id" :label="item.name"
                                       :value="item.id"/>
                        </el-select>
                    </el-form-item>
                </el-col>
                <el-col :span="6">
                    <el-form-item label="课程性质">
                        <el-select v-model="queryDto.nature" placeholder="请选择" style="width: 100%">
                            <el-option v-for="item in natureOptions" :key="item.id" :label="item.name"
                                       :value="item.id"/>
                        </el-select>
                    </el-form-item>
                </el-col>
                <el-col :span="6">
                    <el-form-item label="课程归属">
                        <el-select v-model="queryDto.ownership" placeholder="请选择" style="width: 100%">
                            <el-option v-for="item in ownershipOptions" :key="item.id" :label="item.name"
                                       :value="item.id"/>
                        </el-select>
                    </el-form-item>
                </el-col>
                <el-col :span="6">
                    <el-form-item label="教学模式">
                        <el-select v-model="queryDto.teachingMode" placeholder="请选择" style="width: 100%">
                            <el-option v-for="item in teachingModeOptions" :key="item.id" :label="item.name"
                                       :value="item.id"/>
                        </el-select>
                    </el-form-item>
                </el-col>
                <el-col :span="6">
                    <el-form-item label="考核方式">
                        <el-select v-model="queryDto.assessmentMethod" placeholder="请选择" style="width: 100%">
                            <el-option v-for="item in assessmentMethodOptions" :key="item.id" :label="item.name"
                                       :value="item.id"/>
                        </el-select>
                    </el-form-item>
                </el-col>
                <el-col :span="6">
                    <el-form-item label="代课教师">
                        <el-select v-model="queryDto.teacherId" placeholder="请选择" filterable style="width: 100%">
                            <el-option v-for="item in allteacherList" :key="item.id" :label="item.name"
                                       :value="item.id"/>
                        </el-select>
                    </el-form-item>
                </el-col>
            </el-row>
            <el-row style="display:flex">
                <el-button type="primary" size="small" @click="searchCourse"> 搜索</el-button>
                <el-button size="small" @click="resetData">重置</el-button>
            </el-row>
        </el-form>
    </div>
  <!--添加按钮-->
    <div class="tools-div">
        <el-button type="success" size="small" @click="addShow">添 加</el-button>
    </div>
    <el-dialog v-model="dialogVisible" title="添加或修改" width="50%" draggable @close="handleDialogClose">
        <el-form label-width="100px" :model="course" :rules="rules" ref="courseForm">
            <el-row :gutter="24">
                <el-col :span="12">
                    <el-form-item label="课程名称" prop="name">
                        <el-input v-model="course.name"/>
                    </el-form-item>
                </el-col>
                <el-col :span="12">
                    <el-form-item label="课程代码" prop="code">
                        <el-input v-model="course.code" :disabled="disabled"/>
                    </el-form-item>
                </el-col>
                <el-col :span="12">
                    <el-form-item label="课程学分" prop="credits">
                        <el-input-number v-model="course.credits" :precision="1" :step="0.1" :max="10" :min="0.1"
                                         placeholder="请输入"/>
                    </el-form-item>
                </el-col>
                <el-col :span="12">
                    <el-form-item label="课程学时" prop="period">
                        <el-input-number v-model="course.period" :precision="0" :step="1" :max="100" :min="10"
                                         placeholder="请输入"/>
                    </el-form-item>
                </el-col>
                <el-col :span="12">
                    <el-form-item label="课程类别" prop="category">
                        <el-select v-model="course.category" style="width: 100%" placeholder="请选择">
                            <el-option v-for="item in categoryOptions" :key="item.id" :label="item.name"
                                       :value="item.id"/>
                        </el-select>
                    </el-form-item>
                </el-col>
                <el-col :span="12">
                    <el-form-item label="课程归属" prop="ownership">
                        <el-select v-model="course.ownership" style="width: 100%" placeholder="请选择">
                            <el-option v-for="item in ownershipOptions" :key="item.id" :label="item.name"
                                       :value="item.id"/>
                        </el-select>
                    </el-form-item>
                </el-col>
                <el-col :span="12">
                    <el-form-item label="课程性质" prop="nature">
                        <el-select v-model="course.nature" style="width: 100%" placeholder="请选择">
                            <el-option v-for="item in natureOptions" :key="item.id" :label="item.name"
                                       :value="item.id"/>
                        </el-select>
                    </el-form-item>
                </el-col>
                <el-col :span="12">
                    <el-form-item label="教学模式" prop="teachingMode">
                        <el-select v-model="course.teachingMode" style="width: 100%" placeholder="请选择">
                            <el-option v-for="item in teachingModeOptions" :key="item.id" :label="item.name"
                                       :value="item.id"/>
                        </el-select>
                    </el-form-item>
                </el-col>
                <el-col :span="12">
                    <el-form-item label="考核方式" prop="assessmentMethod">
                        <el-select v-model="course.assessmentMethod" style="width: 100%" placeholder="请选择">
                            <el-option v-for="item in assessmentMethodOptions" :key="item.id" :label="item.name"
                                       :value="item.id"/>
                        </el-select>
                    </el-form-item>
                </el-col>
                <el-col :span="12">
                    <el-form-item label="开课学院" prop="collegeId">
                        <el-select v-model="course.collegeId" style="width: 100%" placeholder="请选择"
                                   @change="handleCollegeChange">
                            <el-option v-for="item in collegeOptions" :key="item.id" :label="item.name"
                                       :value="item.id"/>
                        </el-select>
                    </el-form-item>
                </el-col>
            </el-row>
            <el-form-item label="分配教师" prop="teacherIds">
                <el-select v-model="course.teacherIds" style="width: 100%" placeholder="请先选择开课学院" filterable
                           multiple>
                    <el-option v-for="item in teacherList" :key="item.id" :value="item.id" :label="item.name"/>
                </el-select>
            </el-form-item>
            <el-form-item label="成绩计算项" prop="gradeComponentsIds">
                <el-checkbox-group v-model="course.gradeComponentsIds">
                    <el-checkbox v-for="gradePComponent in allGradeComponentIds" :key="gradePComponent.id"
                                 :label="gradePComponent.id"> {{ gradePComponent.name }}
                    </el-checkbox>
                </el-checkbox-group>
            </el-form-item>
            <el-form-item align="center" label-width="300px">
                <el-button type="primary" @click="submit">提交</el-button>
                <el-button @click="dialogVisible = false">取消</el-button>
            </el-form-item>
        </el-form>
    </el-dialog>

  <!-- 分配菜单的对话框-->
    <el-dialog v-model="dialogGradeComponentsVisible" title="设置成绩项权重" draggable width="20%"
               @close="handleDialogGradeComponentsClose">
        <el-form label-width="80px">
            <el-form-item v-for="gradeComponent in gradeComponentList" :key="gradeComponent.gradeComponentCourseId"
                          :label="gradeComponent.gradeComponentName">
                <el-input-number v-model="gradeComponent.weightage" :precision="2" :step="0.1" :max="0.9" :min="0.1"
                                 controls-position="right" placeholder="请输入"/>
            </el-form-item>
            <el-form-item>
                <span>总权重：{{ totalWeight }}</span>
            </el-form-item>
            <el-form-item>
                <el-button type="primary" @click="doAssign">提交</el-button>
                <el-button @click="dialogGradeComponentsVisible = false">取消</el-button>
            </el-form-item>
        </el-form>
    </el-dialog>

  <!---数据表格-->
    <el-table :data="list" style="width: 100%" border>
        <el-table-column type="index" label="序号" fixed="left" width="60px" align="center"/>
        <el-table-column prop="name" label="课程名称" fixed="left" width="180px"/>
        <el-table-column prop="code" label="课程代码" width="100px"/>
        <el-table-column prop="credits" label="学分" width="60px"/>
        <el-table-column prop="period" label="学时" width="60px"/>
        <el-table-column prop="teacherName" label="代课老师" #default="scope" width="160px">
            <el-tag type="primary" style="margin: 5px" v-for="teacher in scope.row.courseTeacher" :key="teacher.id">
                {{ teacher.teacherName }}
            </el-tag>
        </el-table-column>
        <el-table-column prop="collegeName" label="开课学院" min-width="240px"/>
        <el-table-column prop="categoryName" label="课程类别" min-width="100px"/>
        <el-table-column prop="natureName" label="课程性质" min-width="160px"/>
        <el-table-column prop="ownershipName" label="课程归属" min-width="200px"/>
        <el-table-column prop="teachingMode" label="教学模式" #default="scope" width="90px">
            {{ getTeachingModelName(scope.row.teachingMode) }}
        </el-table-column>
        <el-table-column prop="assessmentMethod" label="考核方式" #default="scope" width="90px">
            {{ getAssessmentMethodName(scope.row.assessmentMethod) }}
        </el-table-column>
        <el-table-column prop="createTime" label="创建时间" width="160px" align="center"/>
        <el-table-column prop="updateTime" label="更新时间" width="160px" align="center"/>
        <el-table-column label="操作" align="center" #default="scope" width="220px" fixed="right">
            <el-button type="primary" size="small" @click="editCourse(scope.row)"> 修改</el-button>
            <el-button type="danger" size="small" @click="deleteById(scope.row)"> 删除</el-button>
            <el-button type="warning" size="small" @click="showAssignGrageComponentsWightage(scope.row)"> 设置权重
            </el-button>
        </el-table-column>
    </el-table>
    <el-pagination v-model:current-page="pageParams.page" v-model:page-size="pageParams.limit"
                   :page-sizes="[5, 10, 20, 50, 100]" @size-change="fetchData" @current-change="fetchData"
                   layout="total, sizes, prev, pager, next" :total="total"/>
</template>

<!-- script部分修改内容 -->
<script setup>
import {onMounted, ref, watch} from 'vue'
import {
    DeleteCourseById,
    FindAllCategory,
    FindAllGradeComponents,
    FindAllNature,
    FindAllOwnership,
    GetCourseListByPage,
    GetGradeComponentIds,
    SaveCourse,
    UpdateCourse,
    UpdateGradeComponentsWeight
} from '@/api/course'
import {ElMessage, ElMessageBox} from 'element-plus'
import {FindAllTeacher, GetAllTeacherByCollegeId} from '@/api/teacher'
import {GetAllCollege} from "@/api/college";

const allteacherList = ref([]);

const fetchTeacherList = async () => {
    const {data} = await FindAllTeacher()
    allteacherList.value = data
}

const teachingModeOptions = ref([
    {id: 1, name: "双语教学"},
    {id: 2, name: "中文教学"},
    {id: 3, name: "英文教学"}
]);

const assessmentMethodOptions = ref([
    {id: 1, name: "考试"},
    {id: 2, name: "考查"}
])

const collegeOptions = ref([])
const teacherList = ref([])
const categoryOptions = ref([])
const natureOptions = ref([])
const ownershipOptions = ref([])
const allGradeComponentIds = ref([])

//表单数据模型
const defaultForm = {
    name: '',
    code: '',
    credits: '',
    period: '',
    collegeId: '',
    category: '',
    nature: '',
    ownership: '',
    teachingMode: '',
    assessmentMethod: '',
    teacherIds: [],
    gradeComponentsIds: []
}

const course = ref(defaultForm) // 使用ref包裹该对象，使用reactive不方便进行重置

const handleDialogClose = () => {
    course.value = {...defaultForm} // 重置数据为默认值
    disabled.value = false
    courseForm.value.clearValidate()
}

// 处理学院选择变化的方法
const handleCollegeChange = async (collegeId) => {
    // 在这里可以添加处理学院选择变化的逻辑
    course.value.teacherIds = []
    await loadTeachersByCollege(collegeId)
}

const loadTeachersByCollege = async (collegeId) => {
    const {data} = await GetAllTeacherByCollegeId(collegeId)
    teacherList.value = data
}
const fetchCollegeList = async () => {
    const {data} = await GetAllCollege()
    collegeOptions.value = data
}
const fetchGradeComponents = async () => {
    const {data} = await FindAllGradeComponents()
    allGradeComponentIds.value = data
}
const fetchCategoryList = async () => {
    const {data} = await FindAllCategory()
    categoryOptions.value = data
}
const fetchNatureList = async () => {
    const {data} = await FindAllNature()
    natureOptions.value = data
}
const fetchOwnershipList = async () => {
    const {data} = await FindAllOwnership()
    ownershipOptions.value = data
}

// 页面加载完毕以后请求后端接口获取数据
onMounted(async () => {
    await fetchData()
    await fetchCollegeList()
    await fetchGradeComponents()
    await fetchCategoryList()
    await fetchNatureList()
    await fetchOwnershipList()
    await fetchTeacherList()
})

const disabled = ref(false)
// 删除数据
const deleteById = row => {
    ElMessageBox.confirm("此操作将永久删除该记录, 是否继续?", "Warning", {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
    }).then(async () => {
        const {code} = await DeleteCourseById(row.id)
        if (code === 200) {
            ElMessage.success('删除成功')
            pageParams.value.page = 1
            await fetchData()
        }
    })
}

// 修改按钮点击事件处理函数
const editCourse = async row => {
    course.value = row
    await loadTeachersByCollege(row.collegeId)
    dialogVisible.value = true
    disabled.value = true
}

const courseForm = ref('courseForm')
// 添加

const submit = async () => {
    // 调用表单实例的方法
    courseForm.value.validate(async (valid) => {
        if (valid) {
            // 表单验证通过，可以进行提交操作
            if (!course.value.id) {
                const {code} = await SaveCourse(course.value)
                if (code === 200) {
                    dialogVisible.value = false
                    ElMessage.success('操作成功')
                    await fetchData()
                }
            } else {
                const {code} = await UpdateCourse(course.value)
                if (code === 200) {
                    dialogVisible.value = false
                    ElMessage.success('操作成功')
                    await fetchData()
                }
            }
        } else {
            // 表单验证失败，显示错误信息或者其他处理
            ElMessage.error('请检查表单数据')
        }
    });

}

// 分页条总记录数
let total = ref(0)
// 定义表格数据模型
let list = ref([])
// 控制对话是否展示的变量
const dialogVisible = ref(false)
//进入添加
const addShow = () => {
    course.value = {...defaultForm}
    teacherList.value = []
    dialogVisible.value = true
}

const dialogGradeComponentsVisible = ref(false)
// 默认选中的菜单数据集合
let courseId = ref()
const gradeComponentList = ref([])
const showAssignGrageComponentsWightage = async row => {
    courseId = row.id
    try {
        const {data} = await GetGradeComponentIds(courseId);
        // 将成绩项列表存储到 gradeComponentList 中
        gradeComponentList.value = data.map(gradeComponent => {
            return {
                gradeComponentId: gradeComponent.gradeComponentId,
                gradeComponentName: gradeComponent.gradeComponentName,
                weightage: gradeComponent.weightage
            };
        });
    } catch (error) {
        console.error('Error fetching grade components:', error);
    }
    dialogGradeComponentsVisible.value = true
}
// 计算总权重的值
const totalWeight = ref(0)

watch(gradeComponentList, (newValue, oldValue) => {
    let sum = 0
    newValue.forEach(gc => {
        if (gc.weightage) {
            sum += parseFloat(gc.weightage)
        }
    })
    totalWeight.value = sum.toFixed(2)
}, {deep: true})
// 在doAssign函数内部
const doAssign = async () => {
    if (totalWeight.value == 1) {
        // 创建一个空数组用于存储成绩项ID和权重的对应关系
        let gradeComponentData = []
        // 遍历gradeComponentList
        for (const gradeComponent of gradeComponentList.value) {
            let gradeComponentObject = {
                gradeComponentId: parseInt(gradeComponent.gradeComponentId),
                weightage: parseFloat(gradeComponent.weightage)
            }
            gradeComponentData.push(gradeComponentObject)
        }
        const gradeComponentDto = {
            courseId: courseId,
            gradeComponentList: gradeComponentData
        }
        const {code} = await UpdateGradeComponentsWeight(gradeComponentDto)
        if (code === 200) {
            dialogGradeComponentsVisible.value = false
            ElMessage.success('操作成功')
            await fetchData()
        }
    } else {
        // 使用Vue 3的方式显示错误信息
        // 这里可以显示一个错误提示，例如使用el-message组件
        ElMessage.error('总权重必须等于1，请重新设置成绩项权重')
    }
}

const handleDialogGradeComponentsClose = () => {
    dialogGradeComponentsVisible.value = false
    courseId = null
    gradeComponentList.value = []
    totalWeight.value = 0
}

//分页数据
const pageParamsForm = {
    page: 1, // 页码
    limit: 5, // 每页记录数
}
const pageParams = ref(pageParamsForm) // 将pageParamsForm包装成支持响应式的对象

// 搜索表单数据
const queryDto = ref({
    name: '',
    collegeId: '',
    category: '',
    nature: '',
    ownership: '',
    teachingMode: '',
    assessmentMethod: '',
    teacherId: ''
})

const getTeachingModelName = (teachingMode) => {
    const model = teachingModeOptions.value.find(option => option.id === teachingMode)
    return model ? model.name : teachingMode
}
const getAssessmentMethodName = (assessmentMethod) => {
    const assessment = assessmentMethodOptions.value.find(option => option.id === assessmentMethod)
    return assessment ? assessment.name : assessmentMethod
}

// 搜索按钮点击事件处理函数
const searchCourse = () => {
    fetchData()
}

// 重置按钮点击事件处理函数
const resetData = async () => {
    queryDto.value = {}
    await fetchTeacherList()
}

// 远程调用后端分页查询接口
const fetchData = async () => {
    const {data} = await GetCourseListByPage(
        pageParams.value.page,
        pageParams.value.limit,
        queryDto.value
    )
    list.value = data.list
    total.value = data.total
}
const rules = {
    name: [
        {required: true, message: '请输入课程名称', trigger: 'blur'}
    ],
    code: [
        {required: true, message: '请输入课程代码', trigger: 'blur'}
    ],
    credits: [
        {required: true, message: '请输入课程学分', trigger: 'blur'},
        {type: 'number', message: '课程学分必须为数字值', trigger: 'blur'},
    ],
    period: [
        {required: true, message: '请输入课程学时', trigger: 'blur'},
        {type: 'number', message: '课程学分必须为数字值', trigger: 'blur'},
    ],
    collegeId: [
        {required: true, message: '请选择院系', trigger: 'blur'}
    ],
    category: [
        {required: true, message: '请选择课程类别', trigger: 'blur'}
    ],
    nature: [
        {required: true, message: '请选择课程性质', trigger: 'blur'}
    ],
    ownership: [
        {required: true, message: '请选择课程归属', trigger: 'blur'}
    ],
    teachingMode: [
        {required: true, message: '请选择授课模式', trigger: 'blur'}
    ],
    assessmentMethod: [
        {required: true, message: '请选择考核方式', trigger: 'blur'}
    ],
    teacherIds: [
        {required: true, message: '请选择任课教师', trigger: 'blur'},
        {validator: validateTeacherIds, trigger: 'blur'}
    ],
    gradeComponentsIds: [
        {required: true, message: '请选择成绩项', trigger: 'blur'}
    ]
}

function validateTeacherIds(rule, value, callback) {
    if (course.value.collegeId == null) {
        callback(new Error('请先选择院系'));
    } else {
        // 其他逻辑验证teacherIds
        callback();
    }
}

watch(() => queryDto.value.collegeId, async (newCollegeId, oldCollegeId) => {
    if (newCollegeId !== oldCollegeId && newCollegeId) {
        const {data} = await GetAllTeacherByCollegeId(newCollegeId)
        allteacherList.value = data
    }
})

</script>

<style scoped>
.search-div {
    margin-bottom: 10px;
    padding: 10px;
    border: 1px solid #ebeef5;
    border-radius: 3px;
    background-color: #fff;
}

.tools-div {
    margin: 10px 0;
    padding: 10px;
    border: 1px solid #ebeef5;
    border-radius: 3px;
    background-color: #fff;
}
</style>
